package com.glory.brepda.activity;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.glory.brepda.R;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.Constant;
import com.glory.brepda.base.MyApp;
import com.glory.brepda.callback.RequestCallBack;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.reflect.TypeToken;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_TextCallback;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_SharePreferencesUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * FileName: SettingActivity
 * Author: XJH
 * Date: 2020/5/12 15:42
 * Description:
 * History:
 */
public class SettingActivity extends BaseActivity {
    @BindView(R.id.ivIp)
    ImageView ivIp;
    @BindView(R.id.tvIP)
    TextView tvIP;
    @BindView(R.id.rlIP)
    RelativeLayout rlIP;
    @BindView(R.id.ivMESIp)
    ImageView ivMESIp;
    @BindView(R.id.tvMESIP)
    TextView tvMESIP;
    @BindView(R.id.rlMESIP)
    RelativeLayout rlMESIP;
    @BindView(R.id.ivFileIp)
    ImageView ivFileIp;
    @BindView(R.id.tvFileIP)
    TextView tvFileIP;
    @BindView(R.id.rlFileIP)
    RelativeLayout rlFileIP;
    @BindView(R.id.tvVersion)
    TextView tvVersion;
    @BindView(R.id.llMain)
    LinearLayout llMain;

    private FreeUI_GeneralFragmentDialog dialog;

    private static String getSerialNumber() {
        String serial = "";
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            serial = (String) get.invoke(c, "ro.serialno");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serial;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_setting;
    }

    @Override
    protected void initView() {
        tvIP.setText(Constant.REQUEST_URL_DEBUG);
        tvFileIP.setText(Constant.FILE_URL);
        tvMESIP.setText(Constant.REQUEST_MES);
        PackageManager manager = getPackageManager();
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = info.versionName;
        tvVersion.setText(version);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("设置");
        return new FreeUI_AddViewEntity(getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY), llMain);
    }

    @OnClick({R.id.rlIP, R.id.rlFileIP, R.id.rlMESIP, R.id.btUploadLog})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.rlIP) {
            dialog = FreeApi_DialogUtils.getScanDialog(this, "请输入服务器地址", Constant.REQUEST_URL_DEBUG, new FreeUI_TextCallback() {
                @Override
                public void onSuccess(String s) {
                    tvIP.setText(s);
                    Constant.REQUEST_URL_DEBUG = s;
                    showToast("保存成功", true);
                    FreeApi_SharePreferencesUtils.setSharePre("DG_CPC_FILE", "REQUEST_URL_DEBUG", s, MyApp.app);
                    dialog.dismiss();
                }
            });
            dialog.show(getSupportFragmentManager(), "WEB_URL_DIALOG");
        }
        if (view.getId() == R.id.rlFileIP) {
            dialog = FreeApi_DialogUtils.getScanDialog(this, "请输入文件地址", Constant.FILE_URL, new FreeUI_TextCallback() {
                @Override
                public void onSuccess(String s) {
                    tvFileIP.setText(s);
                    Constant.FILE_URL = s;
                    showToast("保存成功", true);
                    FreeApi_SharePreferencesUtils.setSharePre("DG_CPC_FILE", "FILE_URL_DEBUG", s, MyApp.app);
                    dialog.dismiss();
                }
            });
            dialog.show(getSupportFragmentManager(), "WEB_URL_DIALOG");
        }
        if (view.getId() == R.id.rlMESIP) {
            dialog = FreeApi_DialogUtils.getScanDialog(this, "请输入服务器地址", Constant.REQUEST_MES, new FreeUI_TextCallback() {
                @Override
                public void onSuccess(String s) {
                    tvMESIP.setText(s);
                    Constant.REQUEST_MES = s;
                    showToast("保存成功", true);
                    FreeApi_SharePreferencesUtils.setSharePre("DG_CPC_FILE", "REQUEST_MES", s, MyApp.app);
                    dialog.dismiss();
                }
            });
            dialog.show(getSupportFragmentManager(), "WEB_URL_DIALOG");
        }
        if (view.getId() == R.id.btUploadLog) {

            if (Constant.AUTHORITY_ENTITY == null) {
                showToast("请先登录", false);
                return;
            }

            File file = new File(FreeApi_StaticMembers.logRootPath);

            File[] files = file.listFiles();
            if (files == null) {
                showToast("没有文件清单！", false);
                return;
            }

            List<File> list = new ArrayList<>();

            for (int i = 0; i < files.length; i++) {
                list.add(files[i]);
            }

            Collections.sort(list, (file1, newFile) -> {
                if (file1.lastModified() > newFile.lastModified()) {
                    return -1;
                } else if (file1.lastModified() == newFile.lastModified()) {
                    return 0;
                } else {
                    return 1;
                }
            });

/*            for (File file1: list ) {
                System.out.println(file1.getName());
            }*/

            String serialNumber = getSerialNumber();
            if (serialNumber.equals("")) {
                serialNumber = "123456";
            }

            Map<String, String> pramas = new HashMap<>();
            Map<String, File> filemaps = new HashMap<>();

            // 装载参数
            pramas.put("SerialNumber", serialNumber);
            // 装载文件
            int Count = list.size() > 1 ? 1 : list.size();
            for (int i = 0; i < Count; i++) {
                filemaps.put(list.get(i).getName() + "_" + Constant.CURRENT_USER, list.get(i));
            }

            RequestCallBack<BaseResponseBean> baseResponseBeanRequestCallBack = new RequestCallBack<BaseResponseBean>(new TypeToken<BaseResponseBean<JSONObject>>() {
            }.getType()) {
                @Override
                public void onFailure(Call call, IOException e) {
                    super.onFailure(call, e);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    super.onResponse(call, response);
                    if (response.code() == 200) {
                        showConfirmDialog(this.Body.getResponse().getHeader().getRESULTMESSAGE());
                    }
                }
            };

            NetUtils.requestCpcPpf("UploadLogFiles", pramas, filemaps, baseResponseBeanRequestCallBack);


            // 删除超过三天的日志文件
            if (list.size() > 3) {
                for (int i = 3; i < list.size(); i++) {
                    try {
                        File fileDel = list.get(i);
                        fileDel.delete();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

//            try {
//                FileInputStream fis = new FileInputStream(list.get(list.size()-1));
//                ByteArrayOutputStream bos = new ByteArrayOutputStream();
//                byte[] b = new byte[1024];
//                int len = -1;
//                while((len = fis.read(b)) != -1) {
//                    bos.write(b, 0, len);
//                }
//                byte[] fileByte = bos.toByteArray();
//                fis.close();

//                FreeUI_EntityCallBack<BaseResponseBean<Object>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<Object>>
//                        (new TypeToken<BaseResponseBean<Object>>() {
//                        }.getType(), getSupportFragmentManager(), this) {
//
//                    @Override
//                    public void onSuccess(Response<BaseResponseBean<Object>> response) {
//                        super.onSuccess(response);
//                        if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
//                            showToast("上传成功",true);
//                        }
//                    }
//
//                    @Override
//                    public void onError(Response<BaseResponseBean<Object>> response) {
//                        super.onError(response);
//                        loadError(response.getException(), "EQUIPMENTID");
//                    }
//                };
//                String fromStream = IOUtils.toString(fileByte, "UTF-8");
//
//                JsonObject map = new JsonObject();
//                map.addProperty("NAME", list.get(Count-1).getName());
//                map.addProperty("VALUE", fromStream);
//                NetUtils.requestPostNet("IF.UploadLog", "UploadLog", SettingActivity.this, map, callBack);

//            } catch (IOException e) {
//                e.printStackTrace();
//            }


        }

    }

}
